from recorder import Inmp441
from max98357 import Max98357
from utils import common


def test_realtime_echo():
    chunk_duration = 0.3
    current_duration = 0
    total_duration = 0.3 * 6

    # 初始化录音设备 (I2S1 RX)
    mic = Inmp441(2, 1, 0)

    # 初始化播放设备 (I2S0 TX)
    # player = Max98357(8, 9, 10, i2s_num=0)

    print(f"开始实时回声，每次录制{chunk_duration}秒,共录制{total_duration}秒...")
    print("说话测试，按Ctrl+C停止...")

    try:
        while True:
            if current_duration >= total_duration:
                print("\n录制结束")
                break

            # 录制音频
            pcm_data = mic.record_pcm(duration_sec=chunk_duration)

            if pcm_data and len(pcm_data) > 0:
                current_duration += chunk_duration
                # player.play_bytes(pcm_data)
            else:
                print("录制失败")

    except KeyboardInterrupt:
        print("\n停止实时回声")
    finally:
        mic.stop()


if __name__ == "__main__":
    common.collect_gc()
    common.print_gc_info()
    
    # 测试实时回声
    test_realtime_echo()
